package com.xywy.beautyand.ACT;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.VolleyError;
import com.xywy.beautyand.R;
import com.xywy.beautyand.base.BaseActivity;
import com.xywy.beautyand.bean.BaseHttpResponse;
import com.xywy.beautyand.bean.ImageUrl;
import com.xywy.beautyand.util.Constants;
import com.xywy.beautyand.util.HttpClientUploadTask;
import com.xywy.beautyand.util.HttpClientUploadTask.HttpClientUploadResponse;
import com.xywy.beautyand.util.ImageUtil;
import com.xywy.beautyand.util.LogUtil;
import com.xywy.beautyand.util.NetUtil;
import com.xywy.beautyand.util.PhotoUtil;
import com.xywy.beautyand.util.ThreadPoolManager;
import com.xywy.beautyand.util.UIUtil;
import com.xywy.beautyand.vollery.OnVolleyResponseListener;
import com.xywy.beautyand.vollery.PostRequest;
import com.xywy.beautyand.widget.DialogItem;

/**
 * *****************************************  
* @Title: AskQuestionAct.java 
* @Package com.xywy.performgirlsandroid.act 
* @Description: TODO(问问题 ) 
* @author smz
* @date 2014-12-31 上午10:56:52 
* @version V1.0   
*******************************************
 */
public class AskQuestionAct extends BaseActivity {
	private TextView right_text;
	private LayoutParams params;
	private ImageUrl imageUrl;
	private EditText free_ask_queston_edit;
	private LinearLayout image_;
	private ImageView free_ask_question_img;
	private TextView edit_text_count;
	private LinearLayout addImageLinear;
	private LinearLayout     image_linear;
	
	private String Tag="ReplayQuestionFragment~~";
	
	protected static final int ASK_QUESSTION_SUCESS = 200;
	
	private int numimg = 0;// 记录上传图片的数量
	private File takingPhoto;
	private String imagePath;
	private List<String> list;// 暂时储存图片的地方
	
	private Bitmap rigitBitmap;
	private String outDirectory;// 压缩后的路径
	private RelativeLayout left_img;
	
	private TextView add_img_tv;
	@Override
	protected void initView(Bundle savedInstanceState) {
      setContentView(R.layout.frag_replay_question);
      list = new ArrayList<String>();
        left_img = (RelativeLayout) findViewById(R.id.left_img);
		TextView middle_title =(TextView) findViewById(R.id.middle_title);
		middle_title.setText("免费咨询");
		right_text = (TextView) findViewById(R.id.right_text);
		right_text.setVisibility(View.VISIBLE);
		right_text.setText("提交 ");
		
		
		
		free_ask_queston_edit = (EditText) findViewById(R.id.free_ask_queston_edit);
		
	    image_linear = (LinearLayout)findViewById(R.id.image_linear);
		image_ = (LinearLayout)findViewById(R.id.image_);
		free_ask_question_img = (ImageView)
				findViewById(R.id.free_ask_question_img);
		edit_text_count = (TextView)findViewById(R.id.edit_text_count);
        add_img_tv = (TextView)findViewById(R.id.add_img_tv);
        
        isplastic = (TextView) findViewById(R.id.isplastic);
        
        noplastic = (TextView) findViewById(R.id.noplastic);
		
		
		int ss = (int) getResources().getDimension(R.dimen.fourty);
		addImageLinear = (LinearLayout)findViewById(R.id.image_);
		params = new LinearLayout.LayoutParams(ss, ss);
		params.leftMargin = 10;
		params.gravity = Gravity.CENTER_VERTICAL;
		imageUrl = new ImageUrl();
		
		Is_plastic=noplastic.getText().toString();
	}

	@Override
	protected void initListener() {
		image_linear.setOnClickListener(this);
		left_img.setOnClickListener(this);
		right_text.setOnClickListener(this);
		
		isplastic.setOnClickListener(this);
		noplastic.setOnClickListener(this);
	}

	@Override
	protected void initData() {

		outDirectory = Environment.getExternalStorageDirectory()
				.getAbsolutePath()
				+ File.separator
				+ "xywy_beauterful"
				+ File.separator + "question";

	}
	
	void AddImageView(Bitmap imgPath) {
		add_img_tv.setVisibility(View.GONE);
		ImageView imageView = new ImageView(context);
		imageView.setImageBitmap(imgPath);
		imageView.setLayoutParams(params);
		addImageLinear.addView(imageView);
	}
	@Override
	public void onClick(View v) {
		super.onClick(v);
		switch (v.getId()) {
		case R.id.image_linear:
			if (numimg < 4) {
				ArrayList<DialogItem> items = new ArrayList<DialogItem>();

				items.add(new DialogItem("拍照", R.layout.bottom_dialog_btn) {
					@Override
					public void onClick() {
						super.onClick();
						takingPhoto = PhotoUtil
								.getPhotoByTaking(AskQuestionAct.this);
						LogUtil.i(Tag, "拍摄相片的路径。。。" + takingPhoto);
					}
				});
				items.add(new DialogItem("从相册中选择", R.layout.bottom_dialog_btn) {
					@Override
					public void onClick() {
						super.onClick();
						PhotoUtil.getPhotoFromAlbum(AskQuestionAct.this);
					}
				});
				//
				items.add(new DialogItem("取消", R.layout.bottom_dialog_cancel));
				UIUtil.showBottomDialog(AskQuestionAct.this, items);

			} else {
				UIUtil.showToast(AskQuestionAct.this, "最多传3张相片哦");
			}
			break;
		case R.id.left_img:
			finish();
			break;
		case R.id.right_text:
			if(checkQuestionInfo())
				sendQuestion();
			break;
		case R.id.isplastic:
			isplastic.setBackgroundResource(R.drawable.login_button_press);
			isplastic.setTextColor(getResources().getColor(R.color.white));
			
			noplastic.setBackgroundResource(R.drawable.lgoin_button_normal);
			noplastic.setTextColor(getResources().getColor(R.color.add_img_tv_color));
			Is_plastic = isplastic.getText().toString();
			
			break;
		case R.id.noplastic:
			isplastic.setBackgroundResource(R.drawable.lgoin_button_normal);
			isplastic.setTextColor(getResources().getColor(R.color.add_img_tv_color));
			
			noplastic.setBackgroundResource(R.drawable.login_button_press);
			noplastic.setTextColor(getResources().getColor(R.color.white));
			Is_plastic = noplastic.getText().toString();
			break;
		default:
			break;
		}
	}
	private void sendimg(String filth) {
		String url = Constants.getSendImgUrl();
		if (NetUtil.hasNetwork(AskQuestionAct.this)) {
			waitingDialog(AskQuestionAct.this, "正在发送~");
			ThreadPoolManager.getInstance()
					.executeTask(
							new HttpClientUploadTask(url, handler, filth,
									"submit_baby"));
		} else {
			UIUtil.showToast(AskQuestionAct.this, "请联网...");
			UIUtil.DissDialog(AskQuestionAct.this, waittingDialog);
		}
	}
	
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		System.out.println("requestCode...的问题" + requestCode);
		switch (requestCode) {
		case Constants.ALB_UM:// 相册
			if (data != null) {
				String photoPath = PhotoUtil.getPathByUri(AskQuestionAct.this,
						data.getData());// 相片的路径
				rigitBitmap = ImageUtil.loadRightDirectioniBitmap(
						ImageUtil.compressImageFromFile(photoPath), photoPath);
				System.out.println("photoPath --" + photoPath);
				imagePath = ImageUtil.compressBmpToFile(rigitBitmap, null);// 压缩图片
				System.out.println("获取的相片的路径" + imagePath);

				sendimg(imagePath);
			}
			break;
		case Constants.PHOTO_GRAPH:// 拍照
			if (takingPhoto != null && takingPhoto.length() > 1024) {

				rigitBitmap = ImageUtil.loadRightDirectioniBitmap(ImageUtil
						.compressImageFromFile(takingPhoto.getAbsolutePath()),
						takingPhoto.getAbsolutePath());// 相片方向矫正
				imagePath = ImageUtil.compressImage(
						takingPhoto.getAbsolutePath(), outDirectory, 500, 500);
				System.out.println("获取相片的路径....................||||"
						+ imagePath + "|||hah");

				sendimg(imagePath);
				break;
			}
		default:
			break;
		}
	}
	
	
	private Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			if (waittingDialog != null && waittingDialog.isShowing())
				waittingDialog.dismiss();
			switch (msg.what) {
			case HttpClientUploadResponse.SUCESS:
				numimg++;
				String imgurl = (String) msg.obj;
				if (list.size() < 3 && list != null) {
					list.add(imgurl);
				}
				AddImageView(rigitBitmap);// 设置完图片
				Toast.makeText(AskQuestionAct.this, "上传成功", 0).show();

				System.out.println("上传成功" + imgurl);
				break;
			case HttpClientUploadResponse.FAIL:
				UIUtil.showToast(AskQuestionAct.this, "上传失败");
				break;
			case HttpClientUploadResponse.ERROR:
				String error = (String) msg.obj;

				System.out.println("获取的返回的错误。。" + error);
				UIUtil.showToast(AskQuestionAct.this, "提问失败");
				break;
			case ASK_QUESSTION_SUCESS:
//				list.clear();
//				Intent intent = new Intent(AskQuestionAct.this,
//						AskDoctorSuessfulAct.class);
//				intent.putExtra("data", data);
//				intent.putExtra("doc_online", doc_online);
//				startActivity(intent);
				UIUtil.showToast(context, "提问成功");
				finish();
				break;
			}
		}
	};
	private TextView isplastic;
	private TextView noplastic;
	private String Is_plastic;
	
	
	/**
	 * 提交问题的借口
	 */
	private void sendQuestion() {
		String Title = free_ask_queston_edit.getText().toString().trim()
				.substring(0, 9)
				+ "...";
		PostRequest<BaseHttpResponse> request = new PostRequest<BaseHttpResponse>(
				Constants.getUrl("club", "Club_ask"), BaseHttpResponse.class,
				new OnVolleyResponseListener<BaseHttpResponse>() {

					@Override
					public void onError(VolleyError volleyError) {
						UIUtil.DissDialog(context, waittingDialog);
						UIUtil.showToast(context, "你的网速有点慢~");
					}

					@Override
					public void onSuccess(BaseHttpResponse response) {
						UIUtil.DissDialog(context, waittingDialog);
						if (response.getState() == 200) {
							Message message = handler.obtainMessage();
							message.what = ASK_QUESSTION_SUCESS;
							handler.sendMessage(message);

						} else {
							UIUtil.showToast(context, response.getError());
						}

					}

				});
		HashMap<String, String> params1 = new HashMap<String, String>();
		params1.put("detail", free_ask_queston_edit.getText().toString().trim()+"||"+noplastic);// 问题细节
		params1.put("sex", "1");// 0男，1女
		params1.put("age", "30");// 不能小于1
		params1.put("userid", Constants.userid);//User.getInstance(context).getUserid()
		params1.put("title", Title);// 问题标题
		params1.put("fromurl", "app_zhengx");

		request.setParams(params1);

		if (list.size() > 0 && list.size() < 3) {
			for (int i = 0; i < list.size(); i++) {
				if (i == 0) {
					params1.put("image", list.get(i));
				} else {
					params1.put("image" + i, list.get(i));
				}
			}
		}
//		 request.setIsParseJson(false);
		executeRequest(request);
	}
	
	private boolean checkQuestionInfo() {
		String content = free_ask_queston_edit.getText().toString().trim();

		if (content.length() <= 0) {
			UIUtil.showToast(context, "问题描述不能为空");
			return false;
		}
		if (content.length() < 10) {
			UIUtil.showToast(context, "问题描述不能少于10个字");
			return false;
		}
		return true;
	}
}
